<!--检查预约登记-->
<template>
  <el-dialog title="病人列表" z-index="1500" :visible.sync="visible" width="844px" :before-close="handleClose" :destroy-on-close="true" class="apply_his_dialog">
    <div class="his_container">
      <!-- <el-input
        style="display: none;"
        v-model="formdata.none"
        @keyup.enter.native="search"
      ></el-input> -->
      <div
        v-loading="loading"
      >
        <div class="his_cont">
          <div class="apply_form">
            <el-form
              rel="form"
              :model="formdata"
              :inline="true"
            >
              <el-form-item prop="patientSource" v-show="isShowFilterTips">
                <div class="pat_source">
                  <el-radio-group
                    v-model="formdata.patientSource"
                    @change="patSourceChange"
                    v-removeAriaHidden
                  >
                    <el-radio
                      v-for="item in patSourceOptions"
                      :key="item.value"
                      :label="item.value"
                    >{{item.name}}</el-radio>
                  </el-radio-group>
                </div>
              </el-form-item>
              <el-form-item prop="patientSource" v-show="!isShowFilterTips">
                <div class="pat_source">
                  <el-radio-group
                    v-model="formdata.patientSource"
                    @change="patSourceChange"
                    v-removeAriaHidden
                  >
                    <el-radio
                      v-for="item in patientSources"
                      :key="item.value"
                      :label="item.value"
                    >{{item.name}}</el-radio>
                  </el-radio-group>
                </div>
              </el-form-item>
              <el-form-item>
                <el-input
                  size="mini"
                  v-model="formdata.patientName"
                  placeholder="患者姓名"
                  @keyup.enter.native="search"
                  clearable
                  autocomplete="off"
                  style="width:198px;"
                >
                  <template slot="prepend">姓名</template>
                </el-input>
              </el-form-item>
              <el-form-item class="mine-time-box">
                <el-input
                  id="formQueryTextIptInDialog"
                  ref="formQueryTextIptInDialog"
                  size="mini"
                  v-model="formdata.queryText"
                  placeholder=""
                  clearable
                  style="width: 100%;"
                  @keyup.enter.native="search"
                >
                  <el-select
                    slot="prepend"
                    size="mini"
                    v-model="formdata.queryWay"
                    placeholder="请选择"
                    style="width: 100px;"
                    @change="queryWayChange"
                  >
                    <el-option
                      v-for="item in queryWayOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-input>
              </el-form-item>
              <el-form-item prop="dateRadio">
                <el-date-picker
                  v-model="formdata.hisFormDate"
                  type="daterange"
                  size="mini"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :clearable="false"
                  :picker-options="pickerOptions"
                  style="max-width: 210px;width: 100%;vertical-align: 2px;"
                  @change="hisFormDateChange"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item style="float:right">
                <span style="font-size:12px;color:red;line-height:30px">表格支持单击选中点击确认</span>
                <el-button
                  type="primary"
                  size="mini"
                  @click="handleConfirm"
                  style="margin-left:2px;width: 70px;">确认</el-button>
                <el-button
                  type="primary"
                  size="mini"
                  @click="search"
                  style="margin-left:2px;width: 70px;">查询</el-button>
                <div class="ky-inlineblock ky-vertical-top">
                  <!-- //   this.$refs.WSCardReader.readerCardOption = this.kyCardReaderOptions -->
                  <WSCardReader ref="WSCardReader" btn-size="mini" @getWSCardReaderMsg="getWSCardReaderMsg"/>
                </div>
                <el-button
                  type="primary"
                  plain
                  size="mini"
                  @click="handleClose"
                  style="margin-left:2px;width: 70px;">关闭</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="his_table">
            <el-table
              ref="tableRef"
              :data="mix_tableData"
              v-if="isShowFilterTips"
              border
              style="width: 100%"
              class="ky-table"
              :row-class-name="tableRowClassName"
              :row-style="tableRowStyle"
              @row-dblclick="handleDlbRowCurr"
              @row-click="handleRowCurr"
            >
              <el-table-column prop="patientSource" label="患者类型" min-width="90" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span class="pat_name" @click="showPatInfo(scope.row)">{{patientSourceLabels[scope.row.patientSource]}}</span>
                </template>
              </el-table-column>
              <el-table-column
                v-for="(cc, index) in tableColumns"
                :key="index"
                :prop="cc.prop"
                :label="cc.label"
                :width="cc.width"
                show-overflow-tooltip>
              </el-table-column>
            </el-table>
            <el-table
              ref="tableRef"
              :data="tableSearchData"
              v-if="!isShowFilterTips"
              border
              style="width: 100%"
              class="ky-table"
              :row-class-name="tableRowClassName"
              :row-style="tableRowStyle"
              highlight-current-row
              @current-change="handleCurrentChange"
            >
              <el-table-column prop="examinationString" label="检查项目" min-width="90" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span class="pat_name">{{scope.row.examinationString}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="patientName" label="姓名" min-width="90" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span class="pat_name">{{scope.row.patientName}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="gender" label="性别" min-width="90" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span class="pat_name">{{gender[scope.row.gender]}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="patientSource" label="患者类型" min-width="90" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span class="pat_name">{{patientSources.filter(item => item.value === scope.row.patientSource).length > 0 ? patientSources.filter(item => item.value === scope.row.patientSource)[0].name : ''}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="applyDepartment" label="申请科室" min-width="90" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span class="pat_name">{{scope.row.applyDepartment}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="applyDateTime" label="申请时间" min-width="90" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span class="pat_name">{{scope.row.applyDateTime}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="applyCode" label="申请单号" min-width="150" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span class="pat_name">{{scope.row.applyCode}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="price" label="金额" min-width="100" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span class="pat_name">{{scope.row.price}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="dengjipartString" label="检查部位" min-width="120" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span class="pat_name">{{scope.row.dengjipartString}}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <!-- 病历信息 -->
        <applyMRITable ref="applymriState"></applyMRITable>
      </div>
    </div>
  </el-dialog>
</template>

<script>
/* eslint-disable */
import { setLocalStorage, getLocalStorage } from '@/utils/localStorage' // removeLocalStorage
import { getKyReaderCardOptions, getDateYMDHMSMS, isNull, getQueryWayByText } from '@/utils/utils'
import { postHisVisitor, getSysHospitalGetModelByCode, supplementaryfeeupdate, getDepList, getItemList, getDepAreaList, getModalityTypeList, postHisExamEncrypt } from '@/api/api'
import { dateFormatter } from '@/utils/validate'
import enc from '@/utils/aes'
import applyMRITable from './applyMRI.vue'
import { Options } from '@/utils/constant'
import WSCardReader from '@/components/WSCardReaderNew/index'
import rtUtil from '@/components/WSCardReaderNew/readerType'
import bus from '@/api/bus'
import virtualTableJs from '@/mixin/virtualTable'
import applyFunction from '@/mixin/applyFunction'
const CHECK_FORM_DEFAULT_KEY = 'CHECK_FORM_DEFAULT'
let logoutFlag = localStorage.getItem('logoutFlag')
const mocklist = [{
  "patient": {
    "patientId": "7707198721361863",
    "masterPatientIndexId": null,
    "idCard": "420101199606171551",
    "ssnCardNo": null,
    "patientName": "朱欣涵",
    "birthDate": "1996-06-17 00:00:00",
    "gender": 1,
    "address": "15846184081",
    "patientPhone": "15187279935",
    "organizationCode": "47000593033030211A1001",
    "organizationNo": null,
    "organizationName": null
  },
  "visit": {
    "visitNo": null,
    "visitNumber": 0,
    "patientAge": "27Y",
    "patientSource": 3,
    "medicalCardNo": null,
    "medicalRecordNo": null,
    "clinicCode": null,
    "hospizationCode": null,
    "visitDateTime": "0001-01-01 00:00:00",
    "visitDeparmentCode": null,
    "visitDeparment": null,
    "attendDoctorCode": null,
    "attendDoctor": null,
    "diagnosis": null,
    "icD10": null,
    "bedNo": "10",
    "wardName": "西",
    "wardNo": null
  },
  "examinations": [{
    "isOverBed": false,
    "checkGroup": null,
    "appointmentType": "",
    "feeType": null,
    "transportType": null,
    "transportTools": null,
    "xno": null,
    "applyCode": "6eab849d8eb242c6a04812b2b77111e0",
    "medicalAdviceNo": null,
    "dep": "US",
    "examClass": "USMF",
    "examClassCode": null,
    "clinicdiagnosis": "无临床诊断，000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
    "chiefComplaint": null,
    "diseasesHistory": "暂无病史，0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
    "physicalSign": null,
    "emergency": 0,
    "examPurpose": null,
    "isEmergency": true,
    "applyDepartment": "放射科",
    "applyDepartmentCode": null,
    "applyDoctor": "管理员",
    "applyDoctorCode": "admin",
    "examText": null,
    "cost": 0,
    "examExecuteDepartmentCode": null,
    "examExecuteDepartment": null,
    "remarkInfo": null,
    "effectiveFlag": true,
    "applyDateTime": "2023-09-22 15:10:12",
    "appointDateTime": null,
    "appointTimePeriod": null,
    "examStatus": 99,
    "feeStatus": true,
    "invoiceNo": null,
    "examItems": [{
      "examNo": null,
      "referenceCode": null,
      "referenceName": null,
      "examItemNo": null,
      "examItemCode": "输卵管超声造影",
      "examItemName": "输卵管超声造影",
      "examMethod": null,
      "price": 0,
      "amount": 1,
      "feeStatus": true,
      "itemType": 0,
      "examParts": [{
        "examPartCode": "输卵管超声造影",
        "examPart": "其它检查",
        "examPartDesc": null
      }]
    }],
    "orderBillDetails": [],
    "applyDataFlag": false,
    "extras": [{
      "key": "Bedside",
      "value": "非床旁"
    }, {
      "key": "EmergencySigns",
      "value": "非急诊"
    }]
  }]
}]
export default {
  components: {
    WSCardReader,
    applyMRITable
  },
  mixins: [virtualTableJs, applyFunction],
  props: {
    checkUrl: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      wsType: '',
      tableDataShowAll: [],
      applyInfoHospital: window.g.applyInfoHospital || '',
      kyCardReaderOptions: '',
      visible: false,
      isCheckExamStatus: this.$store.state.user.appSetting.isCheckExamStatus,
      pubcliKey: this.$store.state.user.pubcliKey,
      privateKey: this.$store.state.user.privateKey,
      loading: false,
      isEncrypt: true,
      userName: this.$store.state.user.userName,
      userCode: this.$store.state.user.userCode,
      hospitalCode: this.$store.state.user.hospitalCode,
      hospitalName: this.$store.state.user.hospitalName,
      isWSCardReader: false, // 判断当前查询，是否为刷卡
      tableDataAll: [],
      tableData: [],
      tableSearchData: [],
      formMoreOpen: false, // 是否展开更多查询条件
      mipVisible: false,
      gender: ['未知性别', '男', '女'],
      formdata: {
        hisFormDate: [dateFormatter(new Date().getTime() - 7 * 24 * 60 * 60 * 1000), dateFormatter(new Date().getTime())],
        queryText: '',
        examClass: '',
        patientSource: 3, // 病人类型 1-门诊 2-住院 3-体检 4-绿检 5-急诊 6-外院、0-未知 默认0
        queryWay: 1, // 查询方式 0 病人id 1 卡号 2 门诊号 3 住院号 4 发票号 5 申请单号 6 身份证号 7 社保卡号 暂时不用 8 手机号 默认0
        dateRadio: '7', // 查询时间，7天，14天 30天
        depArea: '', // 院区过滤
        modalitytype: '', // 设备类型过滤
        cancel: false, // 已取消过滤
        unregistered: false, // 未登记
        returned: false, // 已退单
        none: ''
      },
      patientSourceLabels: ['住院', '门诊', '住院', '体检', '急诊', '外院'], // 附二0的时候默认为住院
      checkAll: false,
      isIndeterminate: false,
      rowCurr: {},
      newRow: {},
      patientRow: {},
      selectRowIds: [],
      checkedPatId: '',
      applyCodes: '',
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      dateRadioOptions: [
        { label: '1天', value: '1' },
        { label: '7天', value: '7' },
        // { label: '14天', value: '14' },
        { label: '30天', value: '30' }
      ],
      depAreaOptions: [], // 院区
      modalitytypeOptions: [], // 设备类型
      depOptions: [], //  科室列表
      queryWayOptions: [
        // 查询方式 0 病人id 1 卡号 2 门诊号 3 住院号 4 发票号 5 申请单号 6 身份证号 7 社保卡号 暂时不用 8 手机号 默认0
        { value: 0, label: 'PID' },
        { value: 1, label: '卡号' },
        { value: 2, label: '门诊号' },
        { value: 3, label: '住院号' },
        { value: 4, label: '发票号' },
        { value: 5, label: '申请单号' },
        { value: 6, label: '身份证号' },
        // { value: 7, label: '社保卡号' },
        { value: 8, label: '手机号' }
      ],
      // 急诊标志
      emergencyTypes: Options.emergencyOptions,
      patientSourceOptions: Options.patientTypeItemOptions,
      appoint_pst: window.g.APPOINT_PST, // [1, 2, 3], // 预约患者类型，默认展示类型 pst:patientsourcetypes
      // 检查预约
      appointTypeOptions: window.g.APPOINT_TYPE_OPTIONS || ['前台登记', '临床预约'], // 预约类型选项
      appoint_type: window.g.APPOINT_TYPE || '前台登记', // 预约类型
      appoint_url: window.g.APPOINT_URL ? window.g.APPOINT_URL + '/index.html?isLogo=1' : '',
      dialogCheckAppoVisible: false,

      // 门诊、内窥镜， 显示病历信息配置
      MRI_examClass: ['内窥镜', '胃肠镜', '胃镜', '肠镜'],

      // 配置显示问题
      lcLoaded: false,
      lcPostMsgList: [],
      patientSources: [{value: 1, name: '门诊'}, {value: 2, name: '住院'}, {value: 3, name: '体检'}, {value: 5, name: '急诊'}, {value: 6, name: '外院'}, {value: 0, name: '全部'}],
      // 表格的列显示
      columnsConfig: Options.checkTableColumnsConfig,
      isShowFilterTips: true,
      rowCurr: {}
    }
  },
  computed: {
    // config配置
    appConfig() {
      return this.$store.state.settings.appConfig
    },
    IS_TRIGGER_PATIENTID() {
      return (this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.IS_TRIGGER_PATIENTID) || window.g.IS_TRIGGER_PATIENTID
    },
    patSourceOptions() {
      let patientSourceOptions = (this.appConfig.checkPatTypeTable || Options.patientTypeItemOptions)
      let psArr = []
      patientSourceOptions.forEach(item => {
        item.name = item.label || item.name
        delete item.label
        psArr.push(item)
      })
      // 1 门诊 2 住院 3 体检 4 绿检 5 急诊 6外院、0未知 默认0
      const arr = psArr.filter(pso => pso.value != 4)
      if (this.formMoreOpen) {
        return arr
      } else if (this.appoint_pst) {
        return arr.filter(pso => this.appoint_pst.includes(pso.value))
      }
      let list = arr.filter(pso => pso.value > 0)
      !this.isShowFilterTips ? list.push({name:'全部', value: 0}) : list.filter(item => item.value != 0)
      return list
    },
    // 列表配置
    tableColumns() {
      return [
        {
          label: 'PID号',
          width: '90',
          prop: 'masterPatientIndexId',
          sort: 0
        },
        {
          label: '姓名',
          width: '90',
          prop: 'patientName',
          show: true,
          sort: 0
        },
        {
          label: '性别',
          width: '50',
          prop: 'genderTxt',
          show: true,
          sort: 1
        },
        {
          label: '年龄',
          width: '60',
          prop: 'patientAge',
          show: true,
          sort: 2
        },
        {
          label: '床号',
          width: '90',
          prop: 'bedNo',
          show: true,
          sort: 2
        },
        {
          label: '住院次数',
          width: '90',
          prop: 'visitNumber', // visitNumber medicalRecordNo
          show: true,
          sort: 2
        },
        {
          label: '检查项目',
          width: '120',
          prop: 'examItemName',
          show: true,
          sort: 2
        },
        {
          label: '申请科室',
          width: '100',
          prop: 'applyDepartment',
          show: true,
          sort: 4
        },
        {
          label: '申请时间',
          width: '160',
          prop: 'applyDateTime',
          show: true,
          sort: 5
        },
        {
          label: '运送方式',
          width: '100',
          prop: 'transportType',
          show: true,
          sort: 7
        },
        {
          label: '检查部位',
          width: '120',
          prop: 'examPart',
          show: true,
          sort: 8
        },
        {
          label: '申请单号',
          width: '200',
          prop: 'applyCode',
          show: true,
          sort: 9
        },
        {
          label: '临床诊断',
          width: '200',
          prop: 'diagnosis',
          show: true,
          sort: 9
        },
      ]
    },
    // 已取消过滤
    cancelShow() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.cancelType
    },
    // 设备过滤
    modalitytypeShow() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.modalityType
    },
    // 区域过滤
    depAreaShow() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.depArea
    },
    // 不自动自动查询的患者来源
    notAutoSearchPatSource() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.unSearchAutoPatientSource
    },
    // 未登记过滤
    unregisteredSHow() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.unregistered
    },
    // 已退单过滤
    returnedShow() {
      return this.appConfig &&
        this.appConfig.baseConfig &&
        this.appConfig.baseConfig.returned
    },
    KYCARDREADER_OPTIONS() {
      let arr = ((this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.kyReaderCardNameArr && this.appConfig.baseConfig.kyReaderCardNameArr.length) && this.appConfig.baseConfig.kyReaderCardNameArr) || []
      let options = getKyReaderCardOptions(arr)
      console.log('KYCARDREADER_OPTIONS=>options', options)
      return (options.length && options) || window.g.KYCARDREADER_OPTIONS || window.g.KYCARDREADER_OPTIONS_FUDING
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.formdata.queryText = ''
        this.$nextTick(() => {
          this.$refs.formQueryTextIptInDialog && this.$refs.formQueryTextIptInDialog.focus()
          // 创建键盘模拟输入的事件监听
          this.$refs.WSCardReader.addInputEventListener('formQueryTextIptInDialog', () => {
            return this.formdata.queryText.trim()
          })
        })
      } else {
        // bus.$off('WSCardReader_msg_sign')
      }
    }
  },
  created() {
    logoutFlag = localStorage.getItem('logoutFlag')
    // 关于不同医院读卡器配置的动态获取
    this.kyCardReaderOptions = this.KYCARDREADER_OPTIONS || window.g.KYCARDREADER_OPTIONS || window.g.KYCARDREADER_OPTIONS_FUDING || rtUtil.defaultType
    // if (this.applyInfoHospital == 'fuding') {
    //   // 如果是福鼎市医院
    //   this.kyCardReaderOptions = window.g.KYCARDREADER_OPTIONS_FUDING || window.g.KYCARDREADER_OPTIONS || rtUtil.defaultType
    // } else {
    //   // 如果是其他医院
    //   this.kyCardReaderOptions = window.g.KYCARDREADER_OPTIONS || rtUtil.defaultType
    // }
    this.refreshThisPatientSourceToQueryWay()
  },
  mounted() {
    // this.$nextTick(() => {
    //   this.$refs.WSCardReader.readerCardOption = this.kyCardReaderOptions
    // }, 500)
    // 查询方式默认选择/初始化
    // patientSource: 1, // 病人类型 1-门诊 2-住院 3-体检 4-绿检 5-急诊 6-外院、0未知 默认0
    // queryWay: 2, // 查询方式 0-病人id 1-卡号 2-门诊号 3-住院号 4-发票号 5-申请单号 6-身份证号 7-社保卡号 暂时不用 8 手机号 默认0
    // this.formdata.queryWay = parseInt(getLocalStorage('queryWay')) ? parseInt(getLocalStorage('queryWay')) : window.g.IS_TRIGGER_PATIENTID ? 0 : !window.g.IS_TRIGGER_OUTPATIENT ? 1 : 2
    // this.formdata.queryWay = window.g.IS_TRIGGER_PATIENTID ? 0 : window.g.IS_TRIGGER_OUTPATIENT ? 2 : (parseInt(getLocalStorage('queryWay'))) || 0
    this.formdata.patientSource = Number(getLocalStorage('yjyy-hisRecordDialog-patientSource') || 3)
    // 玉环医院默认为体检查询
    if (this.hospitalCode === '05766001' || this.hospitalCode === '472841502Q' || this.hospitalCode === '4728420464') {
      this.formdata.patientSource = 3
    }
    this.formdata.queryWay = this.IS_TRIGGER_PATIENTID ? 0 : parseInt(this.patientSourceToqueryWay[this.formdata.patientSource])
    if (this.isShowApplyDepart) {
      this.getDepartment()
    }
  },
  beforeDestroy() {
    bus.$off('WSCardReader_msg')
    this.timeout01 && clearTimeout(this.timeout01)
  },
  methods: {
    // 刷卡返回结果的处理
    getWSCardReaderMsg(res) {
      if (res.searchText) {
        this.formdata.queryWay = getQueryWayByText(res.searchWay)
        this.formdata.queryText = res.searchText
        // this.search()
        this.$nextTick(() => {
          this.search()
        }, 200)
      } else {
        this.formdata.queryText = ''
      }
    },
    handleClose() {
      this.formdata =  {
        hisFormDate: [dateFormatter(new Date().getTime() - 7 * 24 * 60 * 60 * 1000), dateFormatter(new Date().getTime())],
        queryText: '',
        examClass: '',
        // patientSource: 2, // 病人类型 1 门诊 2 住院 3 体检 4 绿检 5急诊 6外院、0未知 默认0
        patientSource: Number(getLocalStorage('yjyy-hisRecordDialog-patientSource') || 3), // 病人类型 1 门诊 2 住院 3 体检 4 绿检 5急诊 6外院、0未知 默认0
        queryWay: 0, // 查询方式 0 病人id 1 卡号 2 门诊号 3 住院号 4 发票号 5 申请单号 6 身份证号 7 社保卡号 暂时不用 8 手机号 默认0
        dateRadio: '7', // 查询时间，7天，14天 30天
        depArea: '', // 院区过滤
        modalitytype: '', // 设备类型过滤
        cancel: false, // 已取消过滤
        unregistered: false, // 未登记
        returned: false, // 已退单
        none: ''
      };
      this.loading = false
      this.visible = false
    },
    async open(row) {
      this.listInit()
      this.visible = true
      // this.getFormDefaultLoaclStorage()
      this.loading = true
      this.tableSearchData = []
      await this.gethospitalInfo(this.hospitalCode)
      this.getDepList(this.hospitalCode)
      // 获取HIS申请单列表数据(补费更新)
      if (row && row.accessionNo) {
        this.patientRow = row
        // console.error('queryWay', queryWay)
        // this.isShowFilterTips = false
        const queryWayChoose = !isNull(row.idCard) ? 6 : !isNull(row.telephone) ? 8 : 0
        this.hospitalCode = row.hospitalCode
        this.formdata.queryWay = queryWayChoose
        this.formdata.queryText = row.idCard || row.telephone || (this.appConfig.baseConfig.mpi ? row.mpi : row.patientId)
        // this.patSourceOptions.filter(pso => pso.value === 0).length === 0 ? this.patSourceOptions.push({name: '全部', value: 0}) : null
        this.formdata.patientSource = 0
        this.handleSupplementary(row)
      } else if (!this.notAutoSearchPatSource || !this.notAutoSearchPatSource.includes(this.formdata.patientSource)) {
        this.search()
      }
      this.loading = false
      // this.appointment({})
      // this.getTypeOptions()
    },
    // 补费登记
    handleSupplementary(row) {
      // 先把这个用户的
      const userInfo = this.$store.state.user.userInfo
      if ((this.formdata.queryText && this.formdata.queryText.trim()) || (this.formdata.patientName && this.formdata.patientName.trim())) {
        this.formdata.hisFormDate = ''
      }
      let myDate = new Date()
      let str = myDate.toTimeString()
      let timeStr = str.substring(0, 8)
      setTimeout(() => {
        let filterPatientInfo = this.$store.state.patient.filterPatientInfo || []
          if (filterPatientInfo.length === 0) {
            let params = {
            patientName: '',
            queryWay: this.formdata.queryWay, // 查询方式 0-病人id 1-卡号 2-门诊号 3-住院号 4-发票号 5-申请单号 6-身份证号 7 社保卡号 暂时不用 8 手机号 默认0
            queryValue:  this.formdata.queryText,
            requestStartDateTime: this.formdata.hisFormDate ? dateFormatter(this.formdata.hisFormDate[0]) : '', // 申请单开始时间
            requestEndDateTime: this.formdata.hisFormDate ? dateFormatter(this.formdata.hisFormDate[1], false) + ' ' + timeStr : '', // 申请单结束时间
            // examClass: this.formdata.examClass, // 检查类型 检查设备
            // organizationNo: this.formdata.depArea, // 影像区域名称
            examClass: '', // 设备类型
            executeDepartMent: '', // 执行科室
            organizationCode: this.hospitalCode, // 申请医院代码
            hospitalCode: this.hospitalCode, // 预约医院代码 如果没传会取申请医院代码
            operateCode: userInfo.userCode, // 操作人编号 可传工号
            operateUser: userInfo.userName, // 操作人姓名
            patientSource: this.formdata.patientSource // 病人类型 1 门诊 2 住院 3 体检 4 绿检 5急诊 6外院、0未知 默认0
          }
          const SM2EncryptData = enc.SM2Encrypt(JSON.stringify(params), this.pubcliKey)
          const data = {
            organizationCode: this.hospitalCode,
            data: '04' + SM2EncryptData
          }
          this.loading = true
          postHisExamEncrypt(data).then(res => {
            this.loading = false
            if (res && res.code === 10000) {
              this.loading = false
              this.getNewTableList(res.content.list)
              // this.getHisTableList(res.content.list)
            } else {
              this.$message.warning(res.message || `查询返回错误：${res.code}！`)
            }
          })
        } else {
          this.getNewTableList(filterPatientInfo)
        }
      }, 200)
    },
    // 修改手机号码
    editPhone() {
      this.$prompt('您确定要修改当前患者的手机号码', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        inputValidator: (val) => {
          if (val === null) {
            return true
          }
          return !(val.length > 11 || val.length < 11)
        },
        inputwarnMessage: '格式不正确'
      }).then(({ value }) => {
        this.rowCurr.patientPhone = value
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    handleCheckAllChange(val) {
      this.mix_tableData.forEach(item => {
        if ((this.checkedPatId || (this.checkAll && this.formdata.queryText && this.formdata.queryWay !== 8 && this.formdata.queryWay !== 4)) &&
          (!this.isCheckExamStatus || (this.isCheckExamStatus && (item.examStatus === -1 || item.examStatus > 3)))
        ) {
          this.checkedPatId = item.patientId
          item.checked = val
        } else {
          item.checked = false
        }
      })
      if (!this.checkedPatId) {
        this.checkAll = false
      }
      if (!this.checkAll) {
        this.cancelCheckedChange()
      }
      this.isIndeterminate = false
    },
    checkallChange() {
      const checkedCount = this.mix_tableData.filter(item => item.checked).length
      const tableCheckList = this.mix_tableData.filter(item => !this.isCheckExamStatus || (this.isCheckExamStatus && (item.examStatus === -1 || item.examStatus > 3))).length
      this.checkAll = checkedCount === tableCheckList && checkedCount > 0
      this.isIndeterminate = checkedCount > 0 && checkedCount < tableCheckList
    },
    getFormDefaultLoaclStorage(set) {
      const checkFormDefault = getLocalStorage(CHECK_FORM_DEFAULT_KEY)
      if (checkFormDefault && !set) {
        const cfd = JSON.parse(checkFormDefault)
        this.appoint_type = cfd.appoint_type
        // this.formdata.patientSource = cfd.patientSource
        if (cfd.dateRadio) {
          this.formdata.dateRadio = cfd.dateRadio
          this.formdata.hisFormDate = [dateFormatter(new Date().getTime() - cfd.dateRadio * 24 * 60 * 60 * 1000), dateFormatter(new Date().getTime())]
        }
      } else {
        const data = {
          appoint_type: this.appoint_type,
          dateRadio: this.formdata.dateRadio,
          patientSource: this.formdata.patientSource
        }
        setLocalStorage(CHECK_FORM_DEFAULT_KEY, JSON.stringify(data))
      }
    },
    getDepAreaList() {
      const params = {
        HospitalCode: this.hospitalCode
      }
      return getDepAreaList(params).then(res => {
        if (res && res.code === 10000) {
          this.depAreaOptions = res.content.list
        }
      })
    },
    getModalityTypeList() {
      const params = {
        HospitalCode: this.hospitalCode,
        DepArea: this.formdata.depArea
      }
      return getModalityTypeList(params).then(res => {
        if (res && res.code === 10000) {
          this.modalitytypeOptions = res.content.list
        }
      })
    },
    depAreaChange() {
      this.formdata.modalitytype = ''
      this.getModalityTypeList()
      this.filterList()
    },
    modalitytypeChange() {
      this.filterInit()
      this.filterList()
    },
    filterList() {
      let dlist = JSON.parse(JSON.stringify(this.tableDataShowAll))
      window.formdata = this.formdata
      let string = ''
      // 执行科室过滤 不用前端过滤，在请求国密的接口 (此处是申请科室)
      if (this.isShowApplyDepart && this.formdata.applyDepartment) {
        string += 'tl.applyDepartment === window.formdata.applyDepartment ) && ('
      }
      // 只住院的查询过滤 原始(未登记)，已作废(已退单)
      if (this.formdata.patientSource === 2 && this.formdata.unregistered && this.returnedShow && !this.checkedPatId) {
        // 未登记的过滤，需要列表没有选择数据时才过滤
        // 未登记
        string += 'tl.examStatus === 5 ) && ('
      }
      if (this.formdata.patientName) {
        // 姓名过滤
        string += 'tl.patientName.indexOf((window.formdata.patientName || \'\').trim()) > -1 ) && ('
      }
      // if (this.formdata.hisFormDate) {
      //   // 日期过滤
      //   const beginTime = new Date(this.formdata.hisFormDate[0])
      //   const endTime = new Date(this.formdata.hisFormDate[1])
      //   string = 'tl => new Date(tl.applyDateTime) >=' + beginTime + '&& new Date(tl.applyDateTime) <=' + endTime + '+) && ('
      // }
      if (string) {
        let intFlag = string.lastIndexOf(' && (')
        string = string.substring(0, intFlag)
        string = 'if(' + string + '{ return true }'
        let fun = new Function('tl', string)
        dlist = dlist.filter(tl => !!fun(tl))
      }
      // if (this.formdata.hisFormDate) {
      //   // 日期过滤
      //   const beginTime = new Date(this.formdata.hisFormDate[0])
      //   const endTime = new Date(this.formdata.hisFormDate[1])
      //   dlist = dlist.filter(tl => new Date(tl.applyDateTime) >= beginTime && new Date(tl.applyDateTime) <= endTime)
      // }
      console.log('dlist', dlist)
      this.vt_init(dlist)
      console.log('filterListnewDataTimeEnd', getDateYMDHMSMS(new Date().getTime()))
    },
    getNewTableList(data) {
      let _data = []
      data.forEach((item, index) => {
        if (index < 600) {
          const examinationString = []
          const dengjipartString = []
          // let priceNum = 0
          let _obj = {
            patient: item.patient,
            visit: item.visit,
            examinations: item.examinations
          }
          Object.keys(item.visit).forEach(k => {
            _obj[`${k}`] = item.visit[k]
          })
          Object.keys(item.patient).forEach(k => {
            _obj[`${k}`] = item.patient[k]
          })
          let priceNum = 0
          Object.keys(item.examinations).forEach(k => {
            _obj[`${k}`] = item.examinations[k]
            item.examinations[k].examItems.forEach(itemExamination => {
              examinationString.push(itemExamination.examItemName)
              priceNum += itemExamination.price
              if (itemExamination.examParts.length > 0) {
                const firstPart = itemExamination.examParts[0]
                itemExamination.dengjipart = firstPart.examPart
                dengjipartString.push(itemExamination.dengjipart)
                itemExamination.dengjipartCode = firstPart.examPartCode
              }
              // 更新检查项字段
              Object.assign(itemExamination, {
                checkpos: itemExamination.examItemName,
                itemPrice: itemExamination.price,
                itemNumber: itemExamination.amount,
                itemNo: itemExamination.examItemNo,
                checkposCode: itemExamination.examItemCode
              })
            })
            _obj = {..._obj, ...item.examinations[k]}
          })
          _obj.examinationString = examinationString.join(',')
          _obj.dengjipartString = dengjipartString.join(',')
          _obj.price = priceNum
          _data.push(_obj)
        }
        // 更新 loading 状态并推送结果
    })
      this.loading = false
      this.tableSearchData = _data
    },
    filterInit() {
      this.handleInit()
    },
    appointTypeChange() {
      // this.getFormDefaultLoaclStorage('set')
      // this.search()
    },
    getTypeOptions() {
      // 如果在配置文件配置，则不在数据字段获取
      if (window.g.APPOINT_TYPE_OPTIONS) return
      // 获取预约来源
      let data = {
        HospitalCode: this.hospitalCode,
        type: '预约来源'
      }
      return new Promise(async resolve => {
        await getItemList(data).then(res => {
          if (res && res.code === 10000) {
            const ats = res.content.list.map(_item => _item.item).filter(ap => ap)
            console.log('ats', ats)
            // !ats.includes('联合预约') ? ats.unshift('联合预约') : ''
            this.appointTypeOptions = ats
            resolve(res)
          }
        })
      })
    },
    dateRadioChange() {
      if (this.formdata.dateRadio) {
        this.formdata.hisFormDate = [dateFormatter(new Date().getTime() - this.formdata.dateRadio * 24 * 60 * 60 * 1000), dateFormatter(new Date().getTime())]
        // this.getFormDefaultLoaclStorage('set')
        this.search()
      }
    },
    hisFormDateChange() {
      this.formdata.dateRadio = ''
    },
    tableRowClassName({ row, rowIndex }) {
      let cls = ''
      if (this.selectRowIds.includes(row.applyCode)) {
        cls += 'select-row '
      }
      return cls
    },
    // 设置列表颜色
    tableRowStyle({ row, rowIndex }) {
      // 患者类型
      const checkPatTypeTable = this.appConfig ? this.appConfig.checkPatTypeTable : ''
      // 标志类型
      const checkTableConfig = this.appConfig ? this.appConfig.checkHisTable : ''
      let bgColor = ''
      let color = ''
      let colorFlag = 0
      // console.log('checkTableConfig===>', checkTableConfig)
      if (row.emergency > 0) {
        if (checkTableConfig && colorFlag === 0) {
          const cObj = checkTableConfig.find(ctc => (~~ctc.value) === row.emergency)
          if (cObj && cObj.colorStatus) {
            bgColor = cObj.bgColor
            color = cObj.fontColor
          }
        }
        return {
          'background-color': bgColor,
          color
        }
      }
      if (checkPatTypeTable && colorFlag === 0) {
        const cObj = checkPatTypeTable.find(ctc => ctc.value === row.patientSource)
        if (cObj && cObj.colorStatus) {
          bgColor = cObj.bgColor
          color = cObj.fontColor
          colorFlag = 1
        }
      }
      if (checkTableConfig && colorFlag === 0) {
        const cObj = checkTableConfig.find(ctc => (~~ctc.value) === row.emergency)
        if (cObj && cObj.colorStatus) {
          bgColor = cObj.bgColor
          color = cObj.fontColor
        }
      }
      // if (!checkPatTypeTable && !checkTableConfig && row.emergency > 0 && color === '' && colorFlag === 0) {
      //   color = '#f00'
      // }
      const sObj = {
        'background-color': bgColor,
        color
      }
      return sObj
    },
    showPatInfo(row) {
      console.log('showPatInfo', row)
    },
    gethospitalInfo(hospitalCode) {
      return new Promise(async resolve => {
        await getSysHospitalGetModelByCode({ hospitalCode }).then(res => {
          this.pubcliKey = res.content.guomiKey
          this.privateKey = res.content.guomiPrivateKey
          if (!window.g.API_ROOT_SCHEDULE) {
            window.g.API_ROOT_SCHEDULE = res.content.hiswebservice
          }
        })
        resolve()
      })
    },
    getDepList(hospitalCode) {
      return new Promise(async resolve => {
        await getDepList({ hospitalCode }).then(res => {
          this.depOptions = res.content.list
        })
        resolve()
      })
    },
    setPatientSourceToqueryWay() {
      this.patientSourceToqueryWay[this.formdata.patientSource || 0] = this.formdata.queryWay || 0
      setLocalStorage('patientSourceToqueryWay', JSON.stringify(this.patientSourceToqueryWay))
    },
    patSourceChange() {
      if (this.patientRow) {
        // this.isShowFilterTips = false
        this.queryWayOptions.forEach(element => {
          if (element.value === 2) {
            element.label = '门诊号'
          }
        })
        // this.handleRowCurr(_row, {})
        if (this.formdata.queryText === '') {
          let queryWayDefault = localStorage.getItem('patientSourceToqueryWay') || {}
          this.formdata.queryWay = !isNull(queryWayDefault) && JSON.parse(queryWayDefault)[this.formdata.patientSource] || this.formdata.queryWay
          if (this.formdata.patientSource == 3) {
            this.queryWayOptions.forEach(element => {
              if (element.value === 2) {
                element.label = '体检号'
              }
            })
          }
        } 
        this.search()
      } else {
        if (window.g.IS_TRIGGER_PATIENTID) {
          console.log('this.formdata.queryWay——if', this.formdata.queryWay)
          this.formdata.queryWay = 0
        } else {
          // this.refreshThisPatientSourceToQueryWay()
          this.formdata.queryWay = this.patientSourceToqueryWay[this.formdata.patientSource]
        }
        localStorage.setItem('yjyy-hisRecordDialog-patientSource', this.formdata.patientSource)
        this.formdata.queryText = ''
        // this.getFormDefaultLoaclStorage('set')
        if (this.formdata.patientSource === 2) {
          this.search()
        } else {
          this.listInit()
        }
      }
    },
    getApplyData() {
      const fd = this.formdata
      const params = {
        patient: {
          patientId: fd.patientId, // 病人id
          masterPatientIndexId: fd.masterPatientIndexId, // PID号
          idCard: fd.idCard, // 身份证
          ssnCardNo: fd.ssnCardNo, // 社保卡
          patientName: fd.patientName, // 姓名
          birthDate: fd.birthDate, // 出生日期
          gender: fd.gender, // 性别 值域：0-未知的性别；1-男性；2-女；9-未说明的性别
          address: fd.address, // 联系地址
          patientPhone: fd.patientPhone, // 联系电话
          organizationCode: fd.organizationCode// 档案所属机构
        },
        visit: {
          visitNo: fd.visitNo, // 就诊号
          visitNumber: fd.visitNumber, // 住院次数
          patientAge: fd.patientAge + fd.patientAgeUnit, // 年龄
          patientSource: fd.patientSource, // 值域：1-门诊；2-住院；3-体检；5-急诊
          medicalCardNo: fd.medicalCardNo, // 就诊卡号
          medicalRecordNo: fd.medicalRecordNo, // 病历号
          clinicCode: fd.clinicCode, // 门诊号
          hospizationCode: fd.hospizationCode, // 住院号
          visitDateTime: fd.visitDateTime, // 就诊时间
          visitDeparmentCode: fd.visitDeparmentCode, // 就诊科室代码
          visitDeparment: fd.visitDeparment, // 就诊科室
          attendDoctorCode: fd.attendDoctorCode, // 接诊医生代码
          attendDoctor: fd.attendDoctor, // 就诊医生
          diagnosis: fd.diagnosis, // 诊断
          icD10: fd.icD10, // icd10
          bedNo: fd.bedNo, // 床号
          wardName: fd.wardName, // 病区
          wardNo: fd.wardNo, // 病区代码
          roomNo: fd.roomNo // 病房号
        },
        examinations: []
      }
      // console.log(1312312)
      const examinationsObj = {
        applyCode: fd.applyCode, // 申请单号
        medicalAdviceNo: fd.medicalAdviceNo, // 医嘱号
        examClass: fd.examClass, // 申请单类型  类型代码:CT/MRI/US等  检查部门
        examClassCode: fd.examClassCode, // 申请单类型代码
        clinicdiagnosis: fd.clinicdiagnosis, // 临床诊断
        chiefComplaint: fd.chiefComplaint, // 主诉
        diseasesHistory: fd.diseasesHistory, // 电子病史
        physicalSign: fd.physicalSign, // 体征
        allergicHistory: fd.allergicHistory, // 过敏史
        drugResistanceHistory: fd.drugResistanceHistory, // 耐药史
        examPurpose: fd.examPurpose, // 检查目的
        isEmergency: fd.isEmergency,
        applyDepartment: fd.applyDepartment, // 申请单科室
        applyDepartmentCode: fd.applyDepartmentCode, // 申请科室代码
        applyDoctor: fd.applyDoctor, // 申请医生
        applyDoctorCode: fd.applyDoctorCode, // 申请医生代码
        examText: fd.examText, // 申请单项目
        cost: fd.cost, // 总价
        examExecuteDepartmentCode: fd.examExecuteDepartmentCode, // 执行科室代码
        examExecuteDepartment: fd.examExecuteDepartment, // 执行科室
        remarkInfo: fd.remarkInfo, // 备注
        effectiveFlag: fd.effectiveFlag,
        applyDateTime: dateFormatter(new Date()), // 申请时间
        examStatus: fd.examStatus, // 值域：0-已登记；1-已检查；2-已报告；3-已审核；4-已作废；5-原始；
        feeStatus: fd.feeStatus, // 是否收费
        invoiceNo: fd.invoiceNo
      }
      params.examinations[0] = examinationsObj

      return params
    },
    handleExecuteDepartMentChange(val) {
      setLocalStorage('yjyy@executeDepart', val)
      this.search()
    },
    search() {
      console.log('into search')
      // 每次查询的时候需清空所选择的患者信息
      // this.$refs.WSCardReader.queryText = this.formdata.queryText
      // 先排除是医保凭证、市民卡、住院卡，然后就是门诊卡
      // if (this.applyInfoHospital == 'fuding') {
      // }
      // 温州市中心医院：
      // 市民卡41位，门诊卡17位，电子医保凭证28位
      // 温附二：住院卡8位
      // 福鼎市医院： 市民卡9位 门诊卡33位 医保卡28位
      let qText = this.formdata.queryText.trim()
      if (!isNull(qText) && (Number(qText) === 0 || Number(qText) === 1)) {
        this.$message.warning('未查到病人信息')
        return
      }
      if (qText) {
        this.$refs.WSCardReader.searchJudge(qText, (res) => {
          console.log('进入回调', res)
          const qw = getQueryWayByText(res.searchWay)
          if (!isNull(qw)) {
            this.formdata.queryWay = qw
          }
          this.doSearch()
        }, (res) => {
          console.log('进入回调, 但不查询', res)
          const qw = getQueryWayByText(res.searchWay)
          if (!isNull(qw)) {
            this.formdata.queryWay = qw
          }
        })
        // if (this.applyInfoHospital == 'fuding') {
        //   if (qText == '*=-*') {
        //     // 市民卡先刷出的是*=-*
        //     this.doSMCard(qText)
        //   } else if (qText.length == 28) {
        //     // 电子医保凭证28位
        //     this.do28Event()
        //   } else if (qText.length == 9) {
        //     // 市民卡9位-福鼎市医院
        //     this.doSearch()
        //   } else if (qText.length == 33) {
        //     // 门诊卡33位,刷出结果10位
        //     this.doCardInit()
        //   } else {
        //     this.doSearch()
        //   }
        // } else {
        //   if (qText == '*=-*') {
        //     // 市民卡先刷出的是*=-*
        //     this.doSMCard(qText)
        //   } else if (qText.length == 28) {
        //     // 医保凭证刷出的是28位
        //     this.do28Event()
        //   } else {
        //     this.doSearch()
        //   }
        // }
      } else {
        this.doSearch()
      }
    },
    doSMCard(qText) {
      // console.log('*=-*市民卡')
      let type = ''
      this.kyCardReaderOptions.forEach(item => {
        if (item.name == '市民卡') {
          type = item.type
        }
      })
      this.$refs.WSCardReader.wsChange(type, qText)
    },
    do28Event() {
      if (this.formdata.queryText.length == 28) { // 医保凭证编码是28位
        this.$nextTick(() => {
          console.warn('光标移出formQueryTextIptInDialog')
          this.$refs.formQueryTextIptInDialog && this.$refs.formQueryTextIptInDialog.blur() // 让该元素所有元素失去光标
          document.activeElement.blur() // 让页面所有元素失去光标
          window.blur() // 让浏览器失去光标
          this.formdata.queryWay = 6
          let type = ''
          this.kyCardReaderOptions.forEach(item => {
            if (item.name == '医保凭证') {
              type = item.type
            }
          })
          this.$refs.WSCardReader.wsChange(type, this.formdata.queryText)
        })
      }
    },
    doCardInit() {
      console.log('==into doCardInit==')
      if (this.kyCardReaderOptions && this.kyCardReaderOptions.length > 0) {
        this.kyCardReaderOptions[1].data.CardId = this.formdata.queryText
        this.$store.dispatch('patient/setCardId', this.formdata.queryText)
        this.$refs.WSCardReader.readerCardOption = this.kyCardReaderOptions
      } else {
        alert('请先在config.js中配置读卡器参数')
      }
      // console.log('into if')dzybpz
      this.$refs.WSCardReader.readerType = 'sbjzfds-fj' // 磁条卡
      this.$refs.WSCardReader.wsInit()
    },
    doSearch() {
      console.log('into doSearch')
      let qText = this.formdata.queryText.trim()
      // 温州市中心医院的门诊卡卡号采用的是门诊卡编码，长度是17位，而其他医院还可能是通过不同长度的编码解析后才得到不同长度的卡号的
      // 这点需注意，不同医院的卡号长度以及卡号读取方式都可能不一样的
      if (qText.length == 17 && (this.applyInfoHospital == 'wzszxyy' || this.hospitalCode === '47052555733030211A1001')) {
        this.formdata.queryWay = 1
        this.formdata.patientSource = 1
      }
      if (qText.length == 20 && this.applyInfoHospital == 'wcxrmyy') {
        this.formdata.queryWay = 1
      }
      this.handleInit()
      this.isShowFilterTips ? this.getHisExamList() : this.handleSupplementary()
    },
    // 获取HIS检查列表
    getHisExamList() {
      const userInfo = this.$store.state.user.userInfo
      if ((this.formdata.queryText && this.formdata.queryText.trim()) || (this.formdata.patientName && this.formdata.patientName.trim())) {
        this.formdata.hisFormDate = ''
      }
      let myDate = new Date()
      let str = myDate.toTimeString()
      let timeStr = str.substring(0, 8)
      const SM2EncryptData = enc.SM2Encrypt(this.formdata.queryText.trim(), this.pubcliKey)
      let queryValue = '04' + SM2EncryptData
      let params = {
        patientName: this.formdata.patientName || '',
        queryWay: this.formdata.queryWay, // 查询方式 0 病人id 1 卡号 2 门诊号 3 住院号 4 发票号 5 申请单号 6 身份证号 7 社保卡号 暂时不用 8 手机号 默认0
        queryValue: queryValue,
        requestStartDateTime: this.formdata.hisFormDate ? dateFormatter(this.formdata.hisFormDate[0]) : '', // 申请单开始时间
        requestEndDateTime: this.formdata.hisFormDate ? dateFormatter(this.formdata.hisFormDate[1], false) + ' ' + timeStr : '', // 申请单结束时间
        // examClass: this.formdata.examClass, // 检查类型 检查设备
        // executeDepartMent: this.formdata.executeDepartMent, // 执行科室
        organizationCode: this.hospitalCode, // 申请医院代码
        hospitalCode: this.hospitalCode, // 预约医院代码 如果没传会取申请医院代码
        operateCode: userInfo.userCode, // 操作人编号 可传工号
        operateUser: userInfo.userName, // 操作人姓名
        patientSource: this.formdata.patientSource, // 病人类型 1 门诊 2 住院 3 体检 4 绿检 5急诊 6外院、0未知 默认0
        StatusCode: 1
      }
      this.rowCurr = {}
      this.checkAll = false
      this.isIndeterminate = false
      this.loading = true
      postHisVisitor(params).then(res => {
        this.loading = false
        if (res && res.code === 10000) {
          if (!res.content.list || !res.content.list.length) {
            this.$message.info(res.message || '未查询到相关数据！')
          }
          // console.log('res.content.list', res.content.list)
          let list = res.content.list && res.content.list != null && res.content.list.length  > 0 ?  res.content.list : []
          if (window.g.isTest) {
            list = mocklist
          }
          this.getHisTableList(list)
        } else {
          !logoutFlag ? this.$message.warning(res.message || `查询返回错误：${res.code}！`) : null
          // this.$message.warning(res.message || `查询返回错误：${res.code}！`)
          let list = []
          console.log('window.g.isTest', window.g.isTest)
          if (window.g.isTest) {
            list = mocklist
          }
          console.log('getList', list)
          this.getHisTableList(list)
        }
      })
    },
    // 查询结果列表数据
    getHisTableList(data) {
      let _data = []
      data.forEach(item => {
        let _obj = {
          patient: item.patient,
          visit: item.visit,
          genderTxt: (!isNull(item.patient.gender)) ? this.getGender(item.patient.gender) : '',
          patientAge: item.visit.patientAge? this.getPatAge('', '', item.visit.patientAge) : '',
          address: item.patient.address,
          price: 0, // 金额
          checked: false, // 列表数据是否选中,
          vip: '否'// 是否vip用户
        }
        Object.keys(item.visit).forEach(k => {
          _obj[`${k}`] = item.visit[k]
        })
        Object.keys(item.patient).forEach(k => {
          _obj[`${k}`] = item.patient[k]
        })
        _data.push(_obj)
      })
      // 未预约显示再上面，已经预约显示再下面（按照预约时间升序排列）
      this.tableDataAll = _data
      this.handleInit()
      this.tableDataShowAll = this.tableDataAll
      this.filterList()
    },
    // 正常查询
    lcPostMessageInit() {
      // examStatus	integer($int32) -1 - HIS取消 0 - 已登记 1 - 已检查 2 - 已报告 3 - 已审核 4 - 已作废 5 - 原始 必填
      console.log('lcPostMsgList', this.lcPostMsgList)
      this.timeout01 = setTimeout(() => {
        if (this.lcPostMsgList.length) {
          const _row = this.lcPostMsgList[0]
          if (!this.isCheckExamStatus || (this.isCheckExamStatus && (_row.examStatus === -1 || _row.examStatus > 3))) {
            this.handleRowCurr(_row, {})
          }
        } else if (this.mix_tableData.length === 1) {
          // 临床预约，加载完成回调
          // 只显示一条数据的时候，默认选中
          const _row = this.mix_tableData[0]
          if (!this.isCheckExamStatus || (this.isCheckExamStatus && (_row.examStatus === -1 || _row.examStatus > 3))) {
            this.handleRowCurr(_row, {})
          }
        }
      }, 200)
    },
    // 自动选择当前查询用户的申请单
    autoCheckedApplyAppo() {
      const checkedArr = []
      let checkedApplyId = ''
      this.tableDataAll.forEach(item => {
        const _item = JSON.parse(JSON.stringify(item))
        // 这里的过滤，是因为公司的环境，是返回所有数据的
        // if (item.idCard === this.formdata.queryText && (!checkedApplyId || checkedApplyId === item.applyCode)) {
        if (!this.isCheckExamStatus || (this.isCheckExamStatus && (_item.examStatus === -1 || _item.examStatus > 3))) {
          _item.checked = true
        }
        checkedArr.push(_item)
        checkedApplyId = _item.applyCode
        this.checkedPatId = _item.patientId
      })
      this.tableDataShowAll = checkedArr
      this.filterList()
      console.log('autoCheckedApplyAppo checkedApplyId', checkedApplyId)
      console.log('autoCheckedApplyAppo checkedArr', checkedArr)
      if (this.checkedPatId) {
        const _obj = this.mix_tableData.find(dd => dd.checked)
        if (_obj) {
          this.rowCurr = _obj
        }
      }
      this.checkallChange()
    },
    // 检查部门改变
    queryWayChange() {
      this.formdata.queryText = ''
      this.setPatientSourceToqueryWay()
      this.$nextTick(() => {
        this.$refs.formQueryTextIptInDialog && this.$refs.formQueryTextIptInDialog.focus()
      }, 100)
    },
    handleInit() {
      this.checkedPatId = ''
      this.applyCodes = ''
      this.selectRowIds = []
      this.rowCurr = {}
    },
    listInit() {
      this.handleInit()
      this.tableDataAll = []
      this.tableDataShowAll = this.tableDataAll
      this.filterList()
    },
    // 获取已选择的申请单数据，传给临床预约页面展示用
    getCheckedPatList(applyCodes) {
      const acs = applyCodes.split('$,$')
      if (acs.length > 0) {
        return acs.map(a => {
          return this.tableDataAll.find(l => l.applyCode === a)
        })
      }
      return null
    },
    handleDlbRowCurr(row, column, event) {
      this.handleRowCurr(row, column, event)
      // this.rowCurr.patientSource = 0
      this.rowCurr.patientSource = this.rowCurr.patientSource === 0 ? 2 : this.rowCurr.patientSource
      bus.$emit('currentRow', this.rowCurr)
      this.handleClose()
    },
    handleCurrentChange(row, column, event) {
      // console.error('row', row)
      let newRow = {}
      if (row) {
        newRow = {
          examList: row.examItems,
          orderBillDetails: row.orderBillDetails,
          patientId: row.patientId,
          patType: this.patSourceOptions.find(item => item.value === row.patientSource).name,
          inpatientId: row.hospizationCode,
          // outPatientId: '',
          // testPatientId: '',
          // magcardType: '',
          // magcardId: '',
          ticketId: row.invoiceNo,
          xno: row.xno,
          applyHospitalCode: this.patientRow.applyHospitalCode,
          applyDateTime: row.applyDateTime,
          doctorMobile: '',
          appointmentType: this.patientRow.nowAppointment,
          examNo: row.applyCode,
          chargeType: row.feeType,
          chargeStatus: row.feeStatus ? '已收费' : '未收费', // 温州市中心医院会出现已收费的为null
          clinicend: row.clinicdiagnosis,
          clinicinfo: row.diseasesHistory,
          chiefComplaint: row.chiefComplaint,
          examPurpose: row.examPurpose,
          price: row.price,
          modalityType: row.examClass,
          // hbsag: '',
          // hiv: '',
          // rpr: '',
          // hcv: '',
          // lisSerumGastric: '',
          // creatinine: '',
          jzlsh: row.visitNumber.toString(),
          checkType: '',
          // isApply: '',
          areaNo: row.organizationNo,
          emergency: row.emergency.toString(),
          floorAddress: row.floorAddress,
          grade: '',
          // radioDoctor: '',
          appointDoctor: row.appointDoctor,
          // privacyLevel: '',
          transportType: row.transportType,
          transportTools: row.transportTools,
          // lmp: '',
          // illnessLevel: '',
          // privacyType: '',
          // privacyDoctorname: '',
          // treatmentType: '',
          // gastroscopicMedicine: '',
          // material: '',
          // medcine: '',
          checkGroup: row.checkGroup,
          // registerRoom: '',
          // beforeAppointmentTime: '',
          extras: row.extras,
          patName: row.patientName,
          patSex: row.gender === 1 ? '男' : (newRow.gender === 2 ? '女' : '未知'),
          patAge: row.patientAge,
          patBirthday: row.birthDate,
          patTelephone: row.patientPhone,
          patAddress: row.address,
          idCard: row.idCard,
          wardnoCode: row.wardNo,
          wardno: row.wardName,
          sqdepCode: row.applyDepartmentCode,
          sqdep: row.applyDepartment,
          doctorCode: row.applyDoctorCode,
          doctor: row.applyDoctor,
          exammark: row.remarkInfo,
          bedno: row.bedNo,
          examinationString: row.examinationString
        }
      }
      this.newRow = newRow
    },
    handleConfirm() {
      if (!this.rowCurr.applyCode && (!this.newRow || !(this.newRow.examNo))) {
        this.$message({
          type: 'warn',
          message: '请选择一条患者记录'
        })
        return false
      } else {
        if (!this.isShowFilterTips) {
          this.loading = true
          let content =`<span>是否将${this.newRow.patName}<span style="color:red;">(${this.newRow.examinationString})</span><br><span>覆盖到</span>${this.patientRow.patientName}<span style="color:red;">(${this.patientRow.checkpos})</span>记录上</span>`
          this.$confirm(content, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            dangerouslyUseHTMLString: true,
            type: 'warning'
          }).then(() => {
            let checkAppointment = JSON.parse(JSON.stringify(this.newRow))
            delete checkAppointment.examinationString
            let params = {
              checkAppointment: checkAppointment,
              accessNo: this.patientRow.accessionNo,
              applyHospitalCode: this.patientRow.applyHospitalCode,
              hospitalCode: this.patientRow.hospitalCode,
              appointmentType: this.patientRow.nowAppointment
            }
            return new Promise(resolve => {
              supplementaryfeeupdate(params).then((res) => {
                this.loading = false
                if (res && res.code === 10000) {
                  resolve(res)
                  this.$message.success(res.message)
                  this.$emit('emitRecordDialog')
                  this.handleClose()
                }
              })
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消选择'
            })
            this.loading = false
          })
        } else {
          bus.$emit('currentRow', this.rowCurr)
          this.handleClose()
        }
      }
    },
    // 触发列表数据
    handleRowCurr(row, column, event) {
      // console.log('handleRowCurr row111111', row)
      // console.log('this.appConfig', this.appConfig.baseConfig.mpi)
      if (this.appConfig.baseConfig && this.appConfig.baseConfig.mpi) {
        this.mipVisible = this.appConfig.baseConfig.mpi
      }
      // console.log('handleRowCurr column', column)
      this.applyMRIChange(row)
      this.applyCodes = ''
      if (column && column.type === 'index' && column.index === 0) {
        if (this.isCheckExamStatus && row.examStatus >= 0 && row.examStatus <= 3) {
          // 从/api/hospital/getappsettings接口获取IsCheckExamStatus的值，
          // 当IsCheckExamStatus=true时，判断申请单的状态ExamStatus >= 0 && ExamStatus <= 3的为已预约数据，
          // 查询号源和预约的时候别传这些已预约数据
          // examStatus	integer($int32) -1 - HIS取消 0 - 已登记 1 - 已检查 2 - 已报告 3 - 已审核 4 - 已作废 5 - 原始 必填
          return
        }
        if (!!this.checkedPatId && this.checkedPatId !== row.patientId) {
          // 如果已经选择，且点击的不是同一个患者
          return
        }
        let tableArr = []
        if (!this.checkedPatId) {
          tableArr = JSON.parse(JSON.stringify(this.tableDataAll.filter(item => item.patientId === row.patientId)))
        } else {
          tableArr = this.mix_tableData
        }
        let patId = ''
        tableArr.forEach(item => {
          if (item.applyCode === row.applyCode) {
            item.checked = !item.checked
          }
          if (item.checked) {
            patId = item.patientId
          }
        })
        this.checkedPatId = patId
        if (!this.checkedPatId) {
          this.tableDataShowAll = this.tableDataAll
          this.filterList()
        } else {
          this.tableDataShowAll = tableArr
          this.filterList()
        }
        this.checkallChange()
        return false
      }
      // this.selectRowIds.length > 1 ? this.selectRowIds = [] : ''
      // if (!this.selectRowIds.includes(row.applyCode)) {
      // }
      this.rowCurr = {
        ...row,
        emergencylabel: this.getEmergencyTip(row.emergency)
      }
      if (this.isCheckExamStatus && row.examStatus >= 0 && row.examStatus <= 3 || this.selectRowIds.includes(row.applyCode)) {
        // 从/api/hospital/getappsettings接口获取IsCheckExamStatus的值，
        // 当IsCheckExamStatus=true时，判断申请单的状态ExamStatus >= 0 && ExamStatus <= 3的为已预约数据，
        // 查询号源和预约的时候别传这些已预约数据
        // examStatus	integer($int32) -1 - HIS取消 0 - 已登记 1 - 已检查 2 - 已报告 3 - 已审核 4 - 已作废 5 - 原始 必填
        return
      }
      // this.appointmentPostMessage(row)
    },
    applyMRIChange(row) {
      this.$refs.applymriState.applyMRITableVisible = false
      if (row.examClass && row.patientSource === 1 && row.medicalCardNo && this.MRI_examClass && this.MRI_examClass.includes(row.examClass)) {
        this.$refs.applymriState.applyMRITableVisible = true
        const mcNo = enc.SM2Encrypt(row.medicalCardNo, this.pubcliKey)
        const data = {
          organizationCode: row.organizationCode, // 申请医院代码
          patientSource: row.patientSource, // 病人类型 1 门诊 2 住院 3 体检 4 绿检 5急诊 6外院、0未知 默认0
          dep: row.examClass, // 检查部门
          medicalCardNo: '04' + mcNo // 就诊卡号 需加密
        }
        console.log('applyMRIChange', data)
        this.$refs.applymriState.init(data)
      }
    },
    cancelCheckedChange() {
      this.handleInit()
      this.tableDataShowAll = this.tableDataAll
      this.filterList()
      this.checkAll = false
      this.isIndeterminate = false
    },
    iframePMBack(data) {
      if (data.type === 1) {
        this.formdata.queryText = ''
        this.handleInit()
        this.getHisExamList()
      } else if (data.type === 0) {
        // 临床预约加载完成执行
        // this.lcLoaded = true
        // this.lcPostMessageInit()
      }
    },
    // wsChange(data) {
    //   if (data.type === 'dzybpz') {
    //     this.formdata.queryWay = 6
    //   } else {
    //     this.formdata.queryWay = 0
    //   }
    // },
    // wsChange(data) {
    //   console.log('wsChange', data)
    //   this.wsType = data.type
    //   // type: 'ybpzsmk',name: '市民卡'; type: 'dzybpz/dzybpz-fj',name: '医保凭证'; type: 'sbjzfds-fj',name: '磁条卡'
    //   // type: ['sbjzykt-fj', 'sbjzykt-fj'],name: '市民卡'
    //   if (data.type === 'dzybpz' || data.type == 'dzybpz-fj') { // 医保凭证
    //     this.formdata.queryWay = 6
    //   } else if (data.type === 'sbjzfds-fj' || data.type === 'sbjzykt-fj') { // 市民卡、磁条卡
    //     this.formdata.queryWay = 1
    //   } else {
    //     this.formdata.queryWay = 1
    //   }
    //   // this.$refs.formQueryTextIptInDialog.focused = true
    //   // this.$refs.formQueryTextIptInDialog.focus()
    //   this.setPatientSourceToqueryWay()
    // },
    // 获取急诊标志
    getEmergencyTip(emerVal) {
      const emergency = this.emergencyTypes.find(et => et.value === emerVal)
      if (emergency) {
        return emergency.label
      }
      return ''
    },
    getSource(row, column, val) {
      // 1 门诊 2 住院 3 体检 4 绿检 5急诊 6外院、0未知 默认0
      const ptObj = Options.patientTypeItemOptions.find(pt => pt.value === val)
      if (ptObj) {
        return ptObj.label
      }
      return '未知'
    },
    getGender(gender) {
      if (!isNull(gender)) {
        if (gender == 1) {
          return '男'
        } else {
          return '女'
        }
      } else {
        return '未知'
      }
    },
    getExamStatusVal(status) {
      // -1 - HIS取消 0 - 已登记 1 - 已检查 2 - 已报告 3 - 已审核 4 - 已作废 5 - 原始 必填
      switch (status) {
        case -1:
          return 'HIS取消'
        case 0:
          return '已登记'
        case 1:
          return '已检查'
        case 2:
          return '已报告'
        case 3:
          return '已审核'
        case 4:
          return '已作废'
        case 5:
          return '未登记'
        default:
          return '未登记'
      }
    },
    getPatAge(row, column, val) {
      if (val.indexOf('Y') > -1) {
        return val.replace('Y', '岁')
      } else if (val.indexOf('M') > -1) {
        return val.replace('M', '月')
      } else if (val.indexOf('D') > -1) {
        return val.replace('D', '日')
      }
      return val
    },
    getParamsString(data) {
      const d = Object.keys(data).map(k => { return `${k}=${data[k]}` })
      return d.join('&')
    }
  }
}
</script>

<style lang="scss" scoped>
$primaryColor: #00A4E9;
$tableThBgColor: #eff6fe;
$warningColor: #ff7600;
$tableSlectedBgColor: #ffe3cc;
$tableDangerColor: #f00;
.his_container{
  margin-top: -20px;
  background-color: #f5f6fa;
  h1{
    margin: 0;
  }
  /deep/ .el-table__body tr.current-row>td{
    background-color: $warningColor;
    color: #fff;
  }
  /deep/ .ky-table th{
    background-color: $tableThBgColor;
    color: #333;
    font-weight: 500;
  }
  /deep/ .el-table__body tr.select-row>td {
    background: $tableSlectedBgColor;
  }
  /deep/ .el-table__body tr.danger-row>td {
    color: $tableDangerColor;
  }
}
.apply_form{
  padding: 6px 10px;
  background-color: #f2f6fc;
  position: relative;
  form{
    justify-content: space-between;
    display: flex;
    flex-wrap: wrap;
  }
  .more_btn{
    font-size: 14px;
    color: #999;
    text-align: center;
    background-color: #fff;
    display: inline-block;
    width: 30px;
    line-height: 30px;
    cursor: pointer;
    &.more_btn_active{
      color: #00A4E9;
    }
    &:hover{
      color: #00A4E9;
    }
  }
  /deep/ .el-form-item__content{
    height: 30px;
    line-height: 30px;
  }
  /deep/ .el-form--inline .el-form-item {
    margin: 4px 0;
  }
  /deep/ .el-radio{
    margin-right: 10px;
  }
  /deep/ .el-button--primary{
    background-color: $warningColor;
    border-color: $warningColor;
  }
  /deep/ .el-button--primary:focus,
  /deep/ .el-button--primary:hover{
    background-color: $warningColor;
  }
  /deep/ .el-radio-button__orig-radio:checked+.el-radio-button__inner{
    background-color: $warningColor;
  }
  /deep/ .el-input--mini .el-input__inner{
    line-height: 30px;
    height: 30px;
  }
  /deep/ .el-range-editor--mini.el-input__inner{
    line-height: 30px;
    height: 30px;
  }
  /deep/ .el-button--mini, .el-button--mini.is-round{
    padding: 8px 15px;
  }
}
.his_table{
  padding:10px 10px 15px;
}
.grid_tit{
  padding: 10px 0;
  font-size: 15px;
  color: #333;
  .tips{
    font-size: 12px;
    color: #999;
  }
  .grid_tit_ckb{
    display: inline-block;
    margin-left: 4px;
    /deep/ .el-checkbox{
      margin-right: 6px;
    }
  }
}
.his_cont{
  padding-bottom: 10px;
  /deep/ .el-radio__label{
    padding-left: 5px;
    font-size: 12px;
  }
  /deep/ .el-radio__input.is-checked+.el-radio__label{
    color: $warningColor;
  }
  /deep/ .el-radio__input .el-radio__inner:hover{
    border-color:  $warningColor;
  }
  /deep/ .el-radio__input.is-checked .el-radio__inner{
    border-color:  $warningColor;
    background:  $warningColor;
  }
  /deep/ .el-table__body-wrapper {
    height: 300px;
    overflow-y: auto;
  }
  /deep/ .el-table td,/deep/ .el-table th{
    padding: 4px 0;
  }
}
.pat_source{
  display: inline-block;
  vertical-align: 1px;
  height: 30px;
  line-height: 28px;
  border: solid 1px #e5e5e5;
  padding: 0 15px 2px 15px;
  background-color: #fff;
}
.check_appo_card{
  /deep/ .el-card__body{
    padding: 0;
  }
}
.pat_info{
  width: 100%;
  padding: 0 10px 10px;
  background-color: #f5f6fa;
  border-top: solid 1px #e5e5e5;
  .pat_info_item{
    display: flex;
    flex-wrap: wrap;
  }
}
// @media screen and (max-width: 1280px) {
//   .his_cont /deep/ .el-table__body-wrapper{
//     height: 200px;
//   }
// }

.his_cont .ky-table /deep/ .el-table__body-wrapper::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 6px;
  /*高宽分别对应横竖滚动条的尺寸*/
  height: 8px;
}
/deep/ .el-tag--dark.el-tag--danger {
  background: #f5534f;
  border-color: #f5534f;
  vertical-align: 2px;
}
.fc_red2 {
  background: #f5534f !important;
}
.apply_his_dialog /deep/ .el-dialog{
  background-color: #f5f6fa;
}
/deep/ .el-dialog__headerbtn{
  top:10px
}
/deep/ .el-dialog__header {
  padding: 10px 20px 10px;
}
/deep/ .el-dialog__body{
  padding: 10px 10px 0;
}
.apply_his_dialog .el-form-item__label {
  font-size: 13px;
  color: #606266;
  line-height: 30px;
  font-weight: 400;
}
.mine-time-box /deep/ .el-input__prefix{
  left: 0;
  line-height: 28px;
  .el-input-group__prepend{
    line-height: 28px;
  }
}
</style>
